/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller.trade;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.controller.BaseController;
import cn.waleychain.exchange.core.entity.KLineUser;
import cn.waleychain.exchange.core.entity.MarketResponseDTO;
import cn.waleychain.exchange.core.entity.TradeNewest;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.feign.TradeDataServiceFeign;
import cn.waleychain.exchange.feign.TradeServiceFeign;
import cn.waleychain.exchange.model.EntrustOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(description = "交易数据相关接口")
@RestController
@RequestMapping("api/v1/tradeData")
public class TradeDataController extends BaseController {

	private static final Logger mLog = LoggerFactory.getLogger(TradeDataController.class);
	
	@Autowired
	private TradeDataServiceFeign tradeDataFeign;
	
	@Autowired
	private TradeServiceFeign tradeFeign;
	
	@RequestMapping(value = "/fetchKLineData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取k线图数据", notes = "获取k线图数据，URL: http://{ip}:{port}/{projectName}/api/v1/tradeData/fetchKLineData", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchKLineData(
			@ApiParam(value = "交易市场ID", required = true) @RequestParam Long marketId, 
			@ApiParam(value = "图表格式(oneminutes 1分钟，fiveminutes 5分钟，fifteenminutes 15分钟，thirtyminutes 30分钟，oneday 1天，sevenday 1周)", required = true) @RequestParam String dataType,
			@ApiParam(value = "图表数据量", required = true) @RequestParam Integer kLimit,
			@RequestHeader String Authorization) throws Exception {

		try {

			Map<String, Object> data = tradeDataFeign.fetchKLineData(marketId, dataType, kLimit);
			
			return DefaultResult.buildSuccessResult(data);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取k线图数据");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/resetKLineUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "将访问k线用户数据存入到缓存", notes = "将访问k线用户数据存入到缓存，URL: http://{ip}:{port}/{projectName}/api/v1/tradeData/fetchKLineData", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult resetKLineUser(
			@ApiParam(value = "交易市场ID", required = true) @RequestParam Long marketId, 
			@ApiParam(value = "图表格式(oneminutes 1分钟，fiveminutes 5分钟，fifteenminutes 15分钟，thirtyminutes 30分钟，oneday 1天，sevenday 1周)", required = true) @RequestParam String dataType,
			@ApiParam(value = "图表数据量", required = true) @RequestParam Integer kLimit,
			@RequestHeader String Authorization) throws Exception {

		try {

			KLineUser kuser = tradeDataFeign.resetKLineUser(session.getId(), marketId, dataType, kLimit);
			
			return DefaultResult.buildSuccessResult(kuser);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "将访问k线用户数据存入到缓存");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchDataDesc", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "根据市场Id 和 日期类型获取图表数据", notes = "根据市场Id 和 日期类型获取图表数据，URL: http://{ip}:{port}/{projectName}/api/v1/tradeData/fetchDataDesc", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchDataDesc(
			@ApiParam(value = "交易市场ID", required = true) @RequestParam Long marketId, 
			@ApiParam(value = "图表格式(oneminutes 1分钟，fiveminutes 5分钟，fifteenminutes 15分钟，thirtyminutes 30分钟，oneday 1天，sevenday 1周)", required = true) @RequestParam String dataType,
			@RequestHeader String Authorization) throws Exception {

		try {

			String data = tradeDataFeign.fetchDataDesc(marketId, dataType);
			
			return DefaultResult.buildSuccessResult(data);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "根据市场Id 和 日期类型获取图表数据");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping({"/fetchNewestEntrust"})
	@ResponseBody
	@ApiOperation(value = "获取最近一个委托买单和卖单", notes = "获取最近一个委托买单和卖单，URL: http://{ip}:{port}/{projectName}/api/v1/tradeData/fetchNewestEntrust", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchNewestEntrust(
			@ApiParam(value = "交易市场ID", required = true) @RequestParam long marketId) throws Exception {
		
		try {

			TradeNewest newest = tradeDataFeign.fetchNewest(marketId);
			
			List<EntrustOrder> buyList = tradeFeign.fetchRecentlyEntrustBuyList(marketId, 1);
			if (buyList != null && buyList.size() > 0) {
				EntrustOrder order = buyList.get(0);
				if (order != null) {
					newest.setBuyOne(order.getPrice());
				}
			}
			List<EntrustOrder> sellList = tradeFeign.fetchRecentlyEntrustSellList(marketId, 1);
			if (sellList != null && sellList.size() > 0) {
				EntrustOrder order = sellList.get(0);
				if (order != null) {
					newest.setSellOne(order.getPrice());
				}
			}
			
			return DefaultResult.buildSuccessResult(newest);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "根据市场Id 和 日期类型获取图表数据");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping({"/fetchTradeMarketByAreaId"})
	@ResponseBody
	@ApiOperation(value = "获取首页交易市场数据", notes = "获取首页交易市场数据，URL: http://{ip}:{port}/{projectName}/api/v1/tradeData/fetchTradeMarketByAreaId", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchTradeMarketByAreaId(
			@ApiParam(value = "交易市场ID", required = true) @RequestParam String areaId) throws Exception {
		
		try {
			
			List<MarketResponseDTO> list = tradeDataFeign.fetchTradeMarketByAreaId(areaId);
			
			return DefaultResult.buildSuccessResult(list);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取首页交易市场数据");
		}

		return DefaultResult.buildFailedResult();
	}
}
